<template>
  <zm-view
    ref="view"
    scroll
    :background="matchColor"
    :custom-style="{ '--bg-color': matchColor, transition: 'background-color 0.2s' }"
    @load-paging="handleLoadReviewList"
    @refresh-paging="handleRefreshReviewList"
  >
    <zm-navbar title="电影" title-color="#ffffff" back-icon-color="#ffffff" :border-bottom="false" :background="matchColor">
      <!-- #ifndef WEB -->
      <zm-button slot="right" text open-type="share">
        <zm-icon name="share-circle" color="#fff" size="32rpx"></zm-icon>
      </zm-button>
      <!-- #endif -->
    </zm-navbar>
    <!-- 顶部信息 -->
    <view class="flex items-center px-24 pt-24 w-screen">
      <view class="relative mr-24">
        <u-image :src="filmInfo.cover" width="240rpx" height="336rpx" radius="12rpx"></u-image>
        <view v-if="filmInfo.trailer" class="play-btn" @click="handlePlayVideo">
          <u-icon name="play-right-fill" color="#333333"></u-icon>
        </view>
      </view>
      <view class="flex flex-col justify-between h-full flex-1 text-white">
        <text class="font-42 font-700 text-row-1">{{ filmInfo.filmName }}</text>
        <text class="mt-12 text-row-2">{{ filmInfo.type | filmType }}</text>
        <view class="text-row-2">
          <view v-for="(version, index) in filmInfo.versions" :key="index" class="version-tag mt-20">{{ version }}</view>
        </view>
        <view class="flex-col flex">
          <text v-if="filmInfo.publishDate" class="mt-16">{{ filmInfo.publishDate }}({{ filmInfo.area }})</text>
          <text v-if="filmInfo.duration" class="mt-16">片长 {{ filmInfo.duration }}分钟</text>
        </view>
        <view class="flex justify-between mt-32">
          <view v-if="isShowScore" class="btn-block">
            <u-rate active-color="#ffb847" size="20rpx" active-icon="star-fill" inactive-icon="star-fill" :count="5" :value="filmInfo.score / 2" readonly></u-rate>
            <text class="score font-28 font-700 ml-14">{{ filmInfo.score }}</text>
          </view>
          <view v-if="isShowWantView" class="btn-block">
            <text class="score font-28 font-bold">{{ filmInfo.wantview | formatNumberWithUnit }}</text>
            <text class="ml-14">人想看</text>
          </view>
          <view class="btn-block" :class="{ 'ml-16': filmInfo.preSaleFlag > 0 }" @click="onClickCollect">
            <zm-icon name="like" size="32rpx" :color="filmInfo.isCollect == 1 ? '#fd4f3d' : '#ffffff'"></zm-icon>
            <text class="text-white font-26 font-700 ml-14">{{ filmInfo.isCollect == 1 ? "已想看" : "想看" }}</text>
          </view>
        </view>
      </view>
    </view>

    <view class="flex flex-col px-24 mt-44 text-white w-screen overflow-hidden">
      <text class="font-32 font-700">剧情简介</text>
      <view class="flex mt-24 overflow-hidden" @click="isExpand = !isExpand">
        <view class="simple-word" :style="[simpleWordStyle]">
          <text class="simple-word-placeholder">{{ filmInfo.simpleWord }}</text>
          <text v-if="isShowExpand" class="expand-button" :class="{ 'is-esxpand': isExpand }">{{ isExpand ? "收起" : "展开" }}</text>
          {{ filmInfo.simpleWord }}
        </view>
      </view>
    </view>

    <view v-if="filmInfo.castList && filmInfo.castList.length" class="flex flex-col px-24 mt-36 text-white w-screen overflow-hidden">
      <view class="flex items-center justify-between">
        <text class="font-32 font-700">演职人员</text>
        <zm-icon-text
          name="arrow"
          size="28rpx"
          color="#c5c5c5"
          text-color="#c5c5c5"
          text-size="24rpx"
          text-left
          :text="`全部${filmInfo.castList.length}`"
          @click="handleToMoreCastList"
        ></zm-icon-text>
      </view>
      <scroll-view class="overflow-hidden radius-16 mt-24" scroll-x :style="{ width: 'calc(100vw - 48rpx)' }">
        <view class="flex">
          <view v-for="(item, index) in filmInfo.castList" :key="index" class="flex flex-col mr-26 w-146" @click="handleClickCast(item, index)">
            <u-image width="146rpx" height="200rpx" radius="12rpx" :src="item.headImg"></u-image>
            <text class="text-white text-row-1">{{ item.actorName }}</text>
            <text v-if="item.roleName" class="role-name font-20 text-row-1">{{ item.roleName }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="flex flex-col px-24 mt-36 w-screen">
      <view class="flex items-center justify-between">
        <view class="font-32 font-700 text-white flex items-center">
          <text>视频</text>
          <text class="font-26 mx-4 font-bold">/</text>
          <text>剧照</text>
        </view>
        <zm-icon-text
          name="arrow"
          size="28rpx"
          color="#c5c5c5"
          text-color="#c5c5c5"
          text-size="24rpx"
          text-left
          :text="`全部${filmInfo.stills.length}张`"
          @click="handleToMoreStills"
        ></zm-icon-text>
      </view>
      <scroll-view class="overflow-hidden radius-16 mt-24" scroll-x :style="{ width: 'calc(100vw - 48rpx)' }">
        <view class="flex radius-16">
          <view v-for="(src, index) in filmInfo.stills" :key="index" class="flex flex-col mr-6" @click="handleClickStills(src, index)">
            <u-image width="438rpx" height="292rpx" error-width="60" error-height="60" :radius="filmInfo.stills.length == 1 ? '16rpx' : ''" :src="src"></u-image>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="review-wrap">
      <view class="flex justify-between items-center">
        <text class="font-32 font-700">观影热评</text>
        <view v-if="filmInfo.isComment != 1" class="review-btn" @click="handleReview">
          <text class="mr-6">写影评</text>
          <u-icon name="edit-pen" size="28rpx" color="#cccccc"></u-icon>
        </view>
      </view>
      <view class="list-wrap">
        <view v-for="(item, index) in reviewList" :key="index" class="item-wrap">
          <view class="flex flex-1 items-center justify-between">
            <u-image width="78rpx" height="78rpx" radius="50%" :src="item.headImg">
              <u-image slot="error" width="78rpx" height="78rpx" radius="50%" :src="useImage('/zuimei-film-oss/1.0.0/images/avatar.png')"></u-image>
            </u-image>
            <view class="flex flex-col flex-1 ml-16">
              <view class="flex flex-1 items-center justify-between">
                <text class="font-28">{{ item.nickName }}</text>
                <view class="flex items-center">
                  <view class="flex items-center" @click="handleAttentionFilm(item, index)">
                    <zm-icon v-if="item.isAtention == 1" name="good-job" size="32rpx" :color="useColor('theme')"></zm-icon>
                    <zm-icon v-else name="good-job-o" size="32rpx"></zm-icon>
                    <text class="font-24 text-999 ml-6 mr-24">{{ item.attentionCount }}</text>
                  </view>
                  <view class="flex relative">
                    <zm-transition mode="fade-zoom" :show="reviewIndex == index">
                      <view class="more-menu">
                        <template v-if="item.isOwer != 1">
                          <text class="click-animation whitespace-nowrap" @click="handleReportReview(item)">举报</text>
                          <view v-if="item.isOwer == 1" class="line"></view>
                        </template>
                        <template v-if="item.isOwer == 1">
                          <text class="click-animation whitespace-nowrap" @click="handelDeitReview(item)">修改</text>
                          <view class="line"></view>
                        </template>
                        <view v-if="item.isOwer == 1" class="click-animation whitespace-nowrap" @click="handelDeleteReview(item)">删除</view>
                      </view>
                    </zm-transition>
                    <zm-icon name="ellipsis" color="#9E9E9E" weight="bold" size="32rpx" @click="onClickReviewMore(index)"></zm-icon>
                  </view>
                </view>
              </view>
              <text class="font-22 text-999">{{ item.createTime | formatShowYearDate("MM-DD HH:mm") }}</text>
            </view>
          </view>
          <text class="flex ml-60 pl-34 pr-40 mt-20 text-line-15 overflow-hidden" :class="{ 'text-row-3': !item.expand }" @click="handleClickReviewContent(index)">{{ item.content }}</text>
        </view>
        <zm-empty :show="reviewList.length == 0" text="评论热度需要你的助力~"></zm-empty>
      </view>
    </view>
    <view v-if="showBuyBtn" class="footer-wrap">
      <zm-button type="primary" size="large" height="100rpx" round @click="handleBuy">选座购票</zm-button>
    </view>
    <!-- 电影预告播放组件 -->
    <film-trailer-popup></film-trailer-popup>
    <!-- 举报内容 -->
    <zm-action-sheet :show.sync="showReport" :actions="reportReasons" description="选择举报原因" @select="handleSelectReportReason"></zm-action-sheet>
    <!-- 颜色分析 -->
    <zm-color-analysis v-if="showColorAnalysis" :url="filmInfo.cover" :max-colors="1" :match-colors="filmCoverColors" @finish="handleOnColorAnalysisFinish"></zm-color-analysis>
  </zm-view>
</template>

<script>
import hook from "@/mixins/hook"
import page from "@/mixins/page"
import { mitt } from "@/utils/mitt"
import { mapGetters } from "vuex"
import { useStyle } from "../../../zuimei/utils/style"
export default {
  filters: {
    filmType(value) {
      return value?.split(",").join(" / ")
    }
  },
  mixins: [hook, page],
  data() {
    return {
      show: false,
      isExpand: false,
      isShowExpand: false,
      showReport: false,
      showColorAnalysis: false,
      matchColor: "#4a4747",
      hideBuyButton: "",
      filmId: "",
      filmCode: "",
      filmInfo: { castList: [], stills: [] },
      reviewList: [],
      reviewIndex: -1,
      collectionFilmList: [], // 收藏电影列表
      reportReasons: [{ title: "广告，抄袭或垃圾信息" }, { title: "人身攻击、恶意言论" }, { title: "违反法律法规" }, { title: "色情、淫秽或低俗内容" }]
    }
  },
  computed: {
    // 判断是否显示选购票按钮
    showBuyBtn() {
      if (this.hideBuyButton == 1) return false
      return this.filmInfo.preSaleFlag == 2 ? false : this.filmInfo.preSaleFlag != 3
    },
    simpleWordStyle() {
      const style = {}
      if (!this.isExpand) {
        style.maxHeight = "calc(36rpx * 4)"
      }
      return useStyle(style)
    },
    isShowWantView() {
      // 热映且评分0显示想看人数
      if (this.filmInfo.preSaleFlag == 3) return false
      if ((this.filmInfo.preSaleFlag == 0 && this.filmInfo.score == 0) || this.filmInfo.preSaleFlag == 1 || this.filmInfo.preSaleFlag == 2) {
        return true
      }
      return false
    },
    isShowScore() {
      return this.filmInfo.preSaleFlag == 0 && this.filmInfo.score > 0 && this.filmInfo.preSaleFlag != 3
    },
    ...mapGetters(["filmCoverColors"])
  },
  onLoad(options) {
    this.filmId = options.filmId
    this.filmCode = options.filmCode
    this.matchColor = options.color || "#4a4747"
    this.hideBuyButton = options.hideBuyButton // 是否隐藏购买按钮
  },
  onShow() {
    this.handleRefresh()
    this.handleShowTips()
  },
  methods: {
    handleRefresh() {
      this.handleGetFilmInfo()
    },
    handleShowTips() {
      const tips = uni.$getCache("review-submit-tips")
      if (tips) {
        uni.$toast(tips)
        uni.$setCache("review-submit-tips")
        this.$refs.view?.refreshPaging()
      }
    },
    // 去购票
    handleBuy() {
      this.toView({
        url: "pages/cinema/cinema-list-film/cinema-list-film",
        params: {
          filmId: this.filmInfo.filmId,
          filmCode: this.filmInfo.filmCode,
          filmName: this.filmInfo.filmName,
          publishDate: this.filmInfo.publishDate
        }
      })
    },
    // 点击收藏
    async onClickCollect() {
      const res = await uni.$api.film.filmCollection({ filmId: this.filmInfo.filmId })
      this.filmInfo.isCollect = res.collectionType
      if (res.collectionType == 1) uni.$toast("已同步至我的想看页面")
      uni.$emit("deco-film-list.refresh")
    },
    async handleGetFilmInfo() {
      this.filmInfo = await uni.$api.film.getFilmInfo({ filmId: this.filmId })
      if (this.filmInfo.bgColor) this.matchColor = this.filmInfo.bgColor
      if (this.filmInfo.version) this.filmInfo.versions = this.filmInfo.version.split(",")
      if (this.filmInfo.score > 0) this.filmInfo.score = this.filmInfo.score / 10
      if (!this.filmInfo.bgColor) this.showColorAnalysis = true
      this.useShare({
        title: this.filmInfo.filmName,
        imageUrl: this.filmInfo.cover
      })
      this.handleOnSimpleWordOpen()
    },
    async handleLoadReviewList(paging, next) {
      const res = await uni.$api.film.getReviewList({ ...paging, filmId: this.filmId })
      this.reviewList = [...this.reviewList, ...res.list]
      this.reviewList = this.reviewList.map((item) => {
        return { ...item, expand: false }
      })
      next({ list: this.reviewList, total: res.total })
    },
    async handleRefreshReviewList(paging, next) {
      const res = await uni.$api.film.getReviewList({ ...paging, filmId: this.filmId })
      this.reviewList = res.list
      this.reviewList = this.reviewList.map((item) => {
        return { ...item, expand: false }
      })
      next({ list: this.reviewList, total: res.count })
    },
    // 播放视频
    handlePlayVideo() {
      const route = this.useCurrentRoute()
      mitt.emit(`${route}-showFilmTrailer`, this.filmInfo.trailer)
    },
    // 点击演员
    handleClickCast(data, index) {
      uni.previewImage({
        current: index,
        urls: this.filmInfo.castList.map((item) => item.headImg)
      })
    },
    // 点击剧照
    handleClickStills(data, index) {
      uni.previewImage({
        current: index,
        urls: this.filmInfo.stills
      })
    },
    onClickReviewMore(index) {
      this.reviewIndex = this.reviewIndex == index ? -1 : index
    },
    // 举报影评
    async handleReportReview(item) {
      this.reviewIndex = -1
      this.reviewId = item.reviewId
      this.showReport = true
    },
    // 点击举报原因
    async handleSelectReportReason(data) {
      await uni.$api.film.reviewReport({ filmId: this.filmId, reviewId: this.reviewId, reportContent: data.title })
      this.showReport = false
      uni.$toast("举报成功，等待审核")
    },
    // 影评点赞
    handleAttentionFilm(item, index) {
      uni.$throttling(
        async () => {
          const res = await uni.$api.film.attentionFilm({ filmId: this.filmId, reviewId: item.reviewId })
          this.reviewList[index].attentionCount = res.isAtention == 1 ? +this.reviewList[index].attentionCount + 1 : +this.reviewList[index].attentionCount - 1
          this.reviewList[index].isAtention = res.isAtention
        },
        1000,
        true
      )
    },
    // 编辑影评
    handelDeitReview(item) {
      this.reviewIndex = -1
      uni.$setCache("review-edit", item)
      this.toView({
        url: "pages/cinema/film-review-edit/film-review-edit",
        params: {
          filmId: this.filmId,
          filmName: this.filmInfo.filmName,
          reviewId: item.reviewId
        }
      })
    },
    // 删除评论
    handelDeleteReview(item) {
      uni.showModal({
        title: "提示",
        content: "确定删除该评论？",
        success: async (res) => {
          if (res.confirm) {
            this.reviewIndex = -1
            await uni.$api.film.delReview({ filmId: this.filmId, reviewId: item.reviewId })
            uni.$toast("删除成功")
            this.handleGetFilmInfo()
            this.$refs.view.refreshPaging()
          }
        }
      })
    },
    // 评论
    handleReview() {
      this.toView({
        url: "pages/cinema/film-review-edit/film-review-edit",
        params: {
          filmId: this.filmId,
          filmName: this.filmInfo.filmName
        }
      })
    },
    // 颜色分析结果
    handleOnColorAnalysisFinish(colors) {
      if (colors?.length) {
        this.matchColor = this.filmInfo.bgColor || colors[0]
      }
    },
    // 全部演职员页面
    handleToMoreCastList() {
      uni.$setCache("performer-list", this.filmInfo.castList)
      this.toView({
        url: "pages/cinema/performer-list/performer-list"
      })
    },
    handleToMoreStills() {
      uni.$setCache("album-list", this.filmInfo.stills)
      this.toView({
        url: "pages/utils/album/album",
        params: {
          col: 3
        }
      })
    },
    handleClickReviewContent(index) {
      this.reviewList[index].expand = !this.reviewList[index].expand
      this.$forceUpdate()
    },
    // 计算影评rect
    handleOnSimpleWordOpen() {
      this.$nextTick(async () => {
        const rect = await this.useRect(".simple-word-placeholder")
        if (rect?.height > 72) {
          this.isShowExpand = true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.play-btn {
  right: 8rpx;
  bottom: 8rpx;
  width: 54rpx;
  height: 54rpx;
  display: flex;
  position: absolute;
  border-radius: 50%;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.5);
}

.version-tag {
  display: inline-flex;
  height: 28rpx;
  font-size: 18rpx;
  color: #ffffff;
  font-weight: bold;
  padding: 4rpx 10rpx;
  border-radius: 4rpx;
  align-items: center;
  margin-right: 10rpx;
  background-color: rgba(0, 0, 0, 0.2);
}

.btn-block {
  flex: 1;
  height: 68rpx;
  display: flex;
  max-width: 210rpx;
  align-items: center;
  border-radius: 10rpx;
  justify-content: center;
  background: rgba(0, 0, 0, 0.2);

  .score {
    color: #ffb847;
  }
}

.w-146 {
  width: 146rpx;
}

.role-name {
  color: #c5c5c5;
}

.review-wrap {
  display: flex;
  margin-top: 30rpx;
  min-height: 500rpx;
  padding: 30rpx 24rpx;
  padding-bottom: 148rpx;
  flex-direction: column;
  background-color: #fff;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;

  .review-btn {
    width: 136rpx;
    height: 50rpx;
    display: flex;
    align-items: center;
    border-radius: 100rpx;
    justify-content: center;
    border: 2rpx solid #cccccc;
  }
}

.list-wrap {
  .item-wrap {
    margin-top: 36rpx;
    .more-menu {
      top: 50%;
      left: -20rpx;
      color: #fff;
      height: 70rpx;
      display: flex;
      position: absolute;
      white-space: nowrap;
      align-items: center;
      padding: 15rpx 24rpx;
      border-radius: 12rpx;
      transform: translate(-100%, -50%);
      background: rgba(0, 0, 0, 0.7);
      .line {
        width: 1rpx;
        height: 40rpx;
        margin: 0 24rpx;
        background-color: #eee;
      }
      &::before {
        content: "";
        position: absolute;
        top: 50%;
        right: 0;
        width: 0;
        height: 0;
        border: 8rpx solid transparent;
        transform: translate(100%, -50%);
        border-left-color: rgba(0, 0, 0, 0.7);
      }
    }
  }
}

.simple-word {
  flex-shrink: 1;
  font-size: 24rpx;
  line-height: 36rpx;
  position: relative;
  text-align: justify;
  &::before {
    content: "";
    float: right;
    width: 0;
    height: 100%;
    font-size: 24rpx;
    margin-bottom: -34rpx;
  }
  .simple-word-placeholder {
    top: 0;
    left: 0;
    right: 0;
    opacity: 0;
    position: absolute;
  }
  .expand-button {
    position: relative;
    float: right;
    clear: both;
    width: 68rpx;
    text-align: right;
    color: #c5c5c5;
    cursor: pointer;
    &.is-esxpand::before {
      content: none;
    }
    &::before {
      content: "...";
      color: #fff;
      position: absolute;
      transform: translateX(-100%);
    }
  }
}

.footer-wrap {
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
  padding: 24rpx;
  position: fixed;
}
</style>
